import { request } from "@/utils/request";
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

// 请求 CategoryList
export const fetchCategoryList = createAsyncThunk(
  "product/categoryList",
  () => {
    return request.post<{
      classList: API.Category[];
    }>("/api/product/getCategoryList", {
      params: { pid: 1004 },
    });
  }
);

// 请求 BrandList
export const fetchBrandList = createAsyncThunk(
  "product/brandList",
  (classId: string) => {
    return request.post<{ brandList: API.Brand[] }>(
      "/api/product/getBrandList",
      {
        params: {
          pid: 1004,
          pageSize: 100,
          classId, // 分类Id
        },
      }
    );
  }
);

// 请求 ProductList
export const fetchProductList = createAsyncThunk(
  "product/productList",
  (params: {
    classId: string;
    brandId: string;
    pageIndex: string;
    pageSize: string;
  }) => {
    return request.post<{
      productList: API.Product[];
    }>("/api/product/getProductList", {
      params: {
        ...params,
        seriesId: 0,
        pid: 1004,
      },
    });
  }
);

export type productState = {
  categoryList: API.Category[];
  brandList: API.Brand[];
  productList: API.Product[];
};

export const productSlice = createSlice({
  name: "product",
  initialState: {
    // 分类数据
    categoryList: [],
    // 品牌数据
    brandList: [],
    // 产品数据
    productList: [],
  } as productState,
  reducers: {},
  extraReducers: (builder) =>
    builder
      .addCase(fetchCategoryList.fulfilled, (state, { payload }) => {
        state.categoryList = payload.classList;
      })
      .addCase(fetchBrandList.fulfilled, (state, { payload }) => {
        state.brandList = payload.brandList;
      })
      .addCase(fetchProductList.fulfilled, (state, { payload }) => {
        state.productList = payload.productList;
      }),
});

export default productSlice.reducer;
